package com.platform.common.shiro;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.common.utils.AjaxUtils;
import com.platform.common.web.vo.AjaxResult;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限验证失败的过滤器
 */
public class ShiroLoginFilter extends PermissionsAuthorizationFilter {

    private ObjectMapper mapper = new ObjectMapper();

    /**
     * shiro认证perms资源失败后回调方法
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //如果是ajax返回指定格式数据
        if (AjaxUtils.isAjax(httpServletRequest)) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            //返回禁止访问json字符串
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            String jsonStr = mapper.writeValueAsString(AjaxResult.loginDue("登录失效"));
            httpServletResponse.getWriter().write(jsonStr);
        }
        //如果是普通请求进行重定向
        else {
            httpServletResponse.sendRedirect("/toLogin");
        }
        return false;
    }

}